import java.util.HashSet;
import java.util.Set;

public class GetIntersectionNodeACM {
    //静态嵌套类
    public static class ListNode{
        int val;
        ListNode next;

        public ListNode(int val){
            this.val =val;
            this.next = null;
        }
    }

    /**
     * 方法一：Hashset
     */
    public ListNode getIntersectionNodeUsingHashSet(ListNode headA, ListNode headB){
        Set<ListNode>visited=new HashSet<>();
        ListNode temp = headA;
        while(temp != null){
            visited.add(temp);
            temp = temp.next;
        }
        temp = headB;
        while(temp != null){
            if(visited.contains(temp)){
                return  temp;
            }
            temp = temp.next;
        }
        return null;
    }

    /**
     * 方法二：双指针
     */
    public ListNode getIntersectionNodeUsingTwoPointers(ListNode headA, ListNode headB){
        if(headA == null || headB == null){
            return null;
        }
        ListNode pA = headA,pB = headB;
        while(pA != pB){
            pA = pA == null ? headB : pA.next;
            pB = pB == null ? headA : pB.next;
        }
        return pA;
    }

    public static void main(String[] args) {
        //创建链表节点
        ListNode common = new ListNode(8);
        common.next = new ListNode(4);
        common.next.next = new ListNode(5);

        ListNode headA = new ListNode(4);
        headA.next = new ListNode(1);
        headA.next.next = common;

        ListNode headB = new ListNode(5);
        headB.next= new ListNode(6);
        headB.next.next = new ListNode(1);
        headB.next.next.next = common;

        GetIntersectionNodeACM solution = new GetIntersectionNodeACM();
        //HashSet方法
        ListNode intersectionUsingHashSet = solution.getIntersectionNodeUsingHashSet(headA,headB);
        //双指针方法
        ListNode intersectionUsingTwoPointers = solution.getIntersectionNodeUsingTwoPointers(headA,headB);

    }
}
